import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
// import 'package:path_provider/path_provider.dart';

class ReadAndWritePage extends StatefulWidget {
  const ReadAndWritePage({Key? key}) : super(key: key);

  @override
  State<ReadAndWritePage> createState() => _ReadAndWritePageState();
}

class _ReadAndWritePageState extends State<ReadAndWritePage> {
   String? _data;
   String? _content;
   final _textController = TextEditingController();
   ///一.记载资源文件中的文本
   Future<void> _loadData() async {
    final txt = await rootBundle.loadString('assets/date.txt');
    print("txt文件: $txt");
    final mp3 = await rootBundle.load("assets/nasa_on_a_mission.mp3");
    var buffer =  mp3.buffer.asUint8List();
    print("mp3.buffer文件: $buffer");
    final arb = await rootBundle.loadString('assets/intl_en.arb');
    print("arb文件: $arb");
    final xml = await rootBundle.loadString('assets/launch_background.xml');
    print("xml文件: $xml");
    final dart = await rootBundle.loadString('assets/dart_test.dart');
    print("dart文件: $dart");

    final jsonDate = await rootBundle.load('assets/jsonTest.json');
    print("jsonDate文件 缓冲: ${jsonDate.buffer}");
    print("jsonDate文件 元素大小（以字节为单位）: ${jsonDate.elementSizeInBytes}");
    print("jsonDate文件 字节长度: ${jsonDate.lengthInBytes}");
    print("jsonDate文件 以字节为单位的偏移量: ${jsonDate.offsetInBytes}");
    print("jsonDate文件 散列码: ${jsonDate.hashCode}");
    print("jsonDate文件 运行时类型: ${jsonDate.runtimeType}");
    final jsonString = await rootBundle.loadString('assets/jsonTest.json');

    final jsonk = await rootBundle.loadStructuredData("assets/jsonTest.json", (String s) async{
      print("读取 ${s}");
      return json.decode(s);
    });
    print("json: $jsonk ${jsonk.runtimeType}");
    ///
    print("==============0");
    ///获取资源的
    var bytes = await rootBundle.load("assets/image.png");
    print("==============1");
    // String dir2 = (await getApplicationSupportDirectory()).path;
    String dir2 = "/data/user/0/com.example.example/files";
    print("==============1.1 ${dir2}");
    ///命名文件名称
    String fileName = "image.png";
    ///获取根路径
    String filePath = "$dir2/$fileName";
    ///获取根路径+名称
    ByteBuffer buffer2 =  bytes.buffer;
    print("==============2");
    ///转为Uint8List数据(字节为单位的偏移量，字节长度)
    Uint8List byte = buffer2.asUint8List(bytes.offsetInBytes, bytes.lengthInBytes);
    print("============bytes: ${bytes}");
    print("============byte: ${byte}");
    ///根据文件路径，组成文件
    File file = await File(filePath).writeAsBytes(byte);
    print("读取和写入图像 ${file.path}");
    setState(() {
      _data = file.path;
    });
  }

   ///二.获取一个绝对文件路径
   Future<String> _getDirPath() async {
     ///获取应用文件目录
     Directory dir = await getApplicationDocumentsDirectory();
     print("dir: $dir ");
     print("dir.path： ${dir.path}");
     print("dir.absolute： ${dir.absolute}");
     print("dir.uri： ${dir.uri}");
     print("dir.runtimeType： ${dir.runtimeType}");
     print("dir.hashCode： ${dir.hashCode}");
     print("dir.isAbsolute： ${dir.isAbsolute}");
     print("dir.parent： ${dir.parent}");
     return dir.path;
   }
   ///向绝对路径中的文件读入数据
   Future<void> _readData() async {
     final dirPath = await _getDirPath();
     final myFile = File('$dirPath/data.txt');
     final data = await myFile.readAsString(encoding: utf8);
     setState(() {
       _content = data;
     });
   }

   ///向绝对路径中的文件写入数据
   Future<void> _writeData() async {
     final dirPath = await _getDirPath();
     final myFile = File('$dirPath/data.txt');
     await myFile.writeAsString(_textController.text);
     _textController.clear();
   }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Column(
        children: [
          Text("文本1:${_data}"),
          const SizedBox(height: 20,),
          Row(
            children: [
              GestureDetector(
                  onTap: (){
                    _loadData();
                  },
                  child: const Text("加载资源文本")),
              const SizedBox(width: 20,),
              GestureDetector(
                  onTap: (){
                    setState((){
                      _data = null;
                    });
                  },
                  child: Text("清空")),
            ],
          ),
          TextField(
            controller: _textController,
            decoration: const InputDecoration(
                helperText: '输入要存储的文本',
            ),
          ),
          const SizedBox(height: 20,),
          Text("文本2：$_content", style: const TextStyle(fontSize: 24, color: Colors.pink)),
          Row(
            children: [
              ElevatedButton(
                onPressed: _writeData,
                child: const Text('写文件'),
              ),
              const SizedBox(width: 20,),
              ElevatedButton(
                onPressed: _readData,
                child: const Text('读文件'),
              ),
            ],
          )
        ],
      ),
    );
  }
}
